package belf.migrate.api.sink.jdbc.helper;

import groovy.lang.GroovyShell;
import groovy.lang.Script;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GroovyScriptExecutor {
    private static final GroovyShell shell = new GroovyShell();
    private static final Map<String, Script> scriptCache = new ConcurrentHashMap<>();

    public static Object executeScript(String scriptText, Map<String, Object> bindingVariables) {
        Script script = scriptCache.computeIfAbsent(scriptText, shell::parse);

        if (bindingVariables != null) {
            bindingVariables.forEach(script::setProperty);
        }

        return script.run();
    }

    public static void main(String[] args) {
        String script = """
            import java.util.Base64
            import org.locationtech.jts.io.WKBReader
            import org.locationtech.jts.geom.Geometry
            import groovy.json.JsonSlurper
            
            def jsonSlurper = new JsonSlurper()
            def jsonObject = jsonSlurper.parseText(value)
            String base64String = jsonObject.wkb
            byte[] byteArray = Base64.getDecoder().decode(base64String)
            WKBReader reader = new WKBReader()
            Geometry geometry = reader.read(byteArray)
            return geometry.toText()
        """;

        Map<String, Object> bindings = Map.of("value", "{\"wkb\":\"AQEAAAA+CjJdYzRcwHYf242Z2UhA\",\"srid\":null}}");
        Object result = executeScript(script, bindings);
        System.out.println("Result: " + result);
    }
}